import { createApp, h, ref } from 'vue'
import { ElDialog, ElButton, ElMessageBox } from 'element-plus'

export default function createPromiseDialog(component) {
  return config => {
    return new Promise((resolve, reject) => {
      function distoryEle() {
        app.unmount(div)
        div.remove()
      }

      const div = document.createElement('div')
      document.body.appendChild(div)

      const defineTitle = ref('这是标题')

      const app = createApp({
        render() {
          return h(
            ElDialog,
            {
              modelValue: true,
              title: config?.title || defineTitle.value,
              'before-close'() {
                ElMessageBox.confirm('确定要关闭吗?', {
                  confirmButtonText: '确认',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    distoryEle()
                    resolve()
                  })
                  .catch(() => {
                    // catch error
                  })
              }
            },
            () => [
              h(component, {
                onConfirm(data) {
                  distoryEle()
                  resolve(data)
                },
                onCancel() {
                  distoryEle()
                  resolve()
                }
              })
            ]
          )
        }
      })

      app.component('ElButton', ElButton)

      app.mount(div)
    })
  }
}
